import React, {useEffect, useState,useRef} from 'react';
import { Form, Button, DatePicker,Divider,Popconfirm,Input, Modal,Row,message, Col,Select} from 'antd';
import moment from 'moment';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import {abnormalType,repairType} from "@/utils/constant";

const {RangePicker} = DatePicker;

const AddForm = (props) => {
  const { onSubmit,onChange, onCancel, loading,visible} = props;
  const [form] = Form.useForm();
  const actionRef = useRef();
  const [clickedCancel, setClickedCancel] = useState(false);
  const [cacheOriginData, setCacheOriginData] = useState({});
  const [tempData, setTempData] = useState([]);
  const [data, setData] = useState([{
    id: 624748504,
    remark: "活动名称一",
    type: 1,
    repairType: 2,
    createTime: "2020-05-26T09:42:56Z",
    key:0
  }]);

  useEffect(() => {
  }, []);

  const onFormCancel = () => {
    form.resetFields();
    onCancel();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({
      ...fieldsValue,
    });
  };

  const getRowByKey = (key, newData) => (newData || data)?.filter((item) => item.key === key)[0];

  const toggleEditable = (e, key) => {
    e.preventDefault();
    const newData = data?.map((item) => ({...item}));
    const target = getRowByKey(key, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = {...target};
        setCacheOriginData(cacheOriginData)
      }
      target.editable = !target.editable;
      setData(newData);
      setTempData(newData);
    }
  };

  const remove = (e, key) => {
    const newData = [...data];
    let datas = newData.filter(item => item.key != key);
    setData(datas);
    setTempData(datas);
  };

  const handleFieldChange = (e, fieldName, key) => {
    const newData = [...data];
    const target = getRowByKey(key, newData);
    if (target) {
      target[fieldName] = e.target ? e.target.value : e;
      setData(newData);
      setTempData(newData);
    }
  };

  const updateRow = (e, rowKey) => {
    e.persist();
    if (clickedCancel) {
      setClickedCancel(false);
      return
    }
    const target = getRowByKey(rowKey) || {};
    toggleEditable(e, rowKey);
    const {isNew, editable, key, ...payload} = target;
    onChange(data);
    setTempData(data);
  };

  const cancel = (e, key) => {
    setClickedCancel(true);
    e.preventDefault();
    const newData = [...data];// 编辑前的原始数据
    let cacheData = [];
    cacheData = newData.map((item) => {
      if (item.key === key) {
        if (cacheOriginData[key]) {
          const originItem = {...item, ...cacheOriginData[key], editable: false};
          delete cacheOriginData[key]
          setCacheOriginData(cacheOriginData)
          return originItem
        }
      }
      return item;
    });
    setData(cacheData);
    setClickedCancel(false);
    setTempData(cacheData);
  };


  const columns = [
    {
      title: '选择日期',
      hideInTable: true,
      dataIndex: 'date',
      renderFormItem: (item, props) => {
        return <RangePicker {...props}/>;
      }
    },
    {
      title: '日期',
      dataIndex: 'createTime',
      hideInSearch: true,
      render: (text) => {
        return text ? moment(text).format('YYYY-MM-DD') : ''
      },
    },
    {
      title: '异常类型',
      dataIndex: 'type',
      hideInSearch: true,
      render: (text) => {
        const res = abnormalType.find((item) => item.value === parseInt(text));
        return res ? res.label : text
      },
    },
    {
      title: '补卡类型',
      dataIndex: 'repairType',
      hideInSearch: true,
      render: (text) => {
        const res = repairType.find((item) => item.value === parseInt(text));
        return res ? res.label : text
      },
    },
    {
      title: '原因',
      hideInSearch: true,
      dataIndex: 'remark',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input
              value={text}
              autoFocus
              onChange={(e) => handleFieldChange(e, 'remark', record.key)}
              placeholder="请输入补卡原因"
            />
          )
        }
        return text
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (text, record) => {
        if (!!record.editable && loading) {
          return null
        }
        if (record.editable) {
          return (
            <span>
              <a onClick={(e) => updateRow(e, record.key, record.oid)}>保存</a>
              <Divider type="vertical"/>
              <a onClick={(e) => cancel(e, record.key)}>取消</a>
            </span>
          )
        }
        return (
          <span>
            <a onClick={(e) => toggleEditable(e, record.key)}>编辑</a>
            <Divider type="vertical"/>
            <Popconfirm title="是否要删除此行？" cancelText='取消' okText='确认' onConfirm={(e) => remove(e, record.key)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        )
      }
    },
  ];

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
          <Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button>
      </>
    )
  };


  return (
    <Modal
      maskClosable={false}
      width={'60%'}
      destroyOnClose
      centered
      title={'补卡申请'}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        dataSource={data}
        options={false}
        toolBarRender={false}
        columns={columns}
      />
    </Modal>
  )
};

export default AddForm;
